<template>
  <div class="mock-form-container">
    <div class="page-header">
      <div class="header-left">
        <el-button @click="goBack" icon="ArrowLeft">返回</el-button>
        <h2>{{ isEdit ? '编辑' : '创建' }}Mock API</h2>
      </div>
      <el-button type="primary" @click="saveMockAPI" :loading="saving">保存</el-button>
    </div>

    <el-card class="form-card" shadow="never" v-loading="loading">
      <el-form :model="mockForm" label-width="100px" :rules="rules" ref="formRef">
        <!-- 基本信息 -->
        <el-divider content-position="left">基本信息</el-divider>
        <el-form-item label="API名称" prop="name">
          <el-input v-model="mockForm.name" placeholder="请输入API名称"></el-input>
        </el-form-item>
        <el-form-item label="请求路径" prop="path">
          <el-input v-model="mockForm.path" placeholder="请输入请求路径，例如：/api/users"></el-input>
        </el-form-item>
        <el-form-item label="请求方法" prop="method">
          <el-select v-model="mockForm.method" placeholder="请选择请求方法">
            <el-option label="GET" value="GET"></el-option>
            <el-option label="POST" value="POST"></el-option>
            <el-option label="PUT" value="PUT"></el-option>
            <el-option label="DELETE" value="DELETE"></el-option>
            <el-option label="PATCH" value="PATCH"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="mockForm.description" type="textarea" placeholder="请输入API描述"></el-input>
        </el-form-item>

        <!-- 响应配置 -->
        <el-divider content-position="left">响应配置</el-divider>
        <div v-for="(response, index) in mockForm.responses" :key="index" class="response-item">
          <div class="response-header">
            <h3>响应 #{{ index + 1 }}</h3>
            <div class="response-actions">
              <el-tag v-if="response.isDefault" type="success" size="small" effect="plain">默认响应</el-tag>
              <el-button 
                type="danger" 
                size="small" 
                icon="Delete" 
                circle 
                @click="removeResponse(index)"
                v-if="mockForm.responses.length > 1"
              ></el-button>
            </div>
          </div>
          
          <el-form-item :label="'状态码'">
            <el-input-number v-model="response.statusCode" :min="100" :max="599"></el-input-number>
          </el-form-item>
          
          <el-form-item :label="'内容类型'">
            <el-select v-model="response.contentType" placeholder="请选择内容类型">
              <el-option label="application/json" value="application/json"></el-option>
              <el-option label="text/plain" value="text/plain"></el-option>
              <el-option label="text/html" value="text/html"></el-option>
              <el-option label="application/xml" value="application/xml"></el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item :label="'响应头'">
            <el-input 
              v-model="response.headers" 
              type="textarea" 
              placeholder="请输入响应头，JSON格式"
              :rows="3"
            ></el-input>
          </el-form-item>
          
          <el-form-item :label="'响应体'">
            <el-input 
              v-model="response.body" 
              type="textarea" 
              placeholder="请输入响应体"
              :rows="5"
            ></el-input>
          </el-form-item>
          
          <el-form-item :label="'延迟(毫秒)'">
            <el-input-number v-model="response.delay" :min="0" :max="10000"></el-input-number>
          </el-form-item>
          
          <el-form-item :label="'默认响应'">
            <el-switch v-model="response.isDefault" @change="handleDefaultChange(index)"></el-switch>
          </el-form-item>
          
          <el-divider v-if="index < mockForm.responses.length - 1"></el-divider>
        </div>
        
        <div class="add-response">
          <el-button type="primary" plain @click="addResponse">添加响应</el-button>
        </div>

        <!-- 匹配规则 -->
        <el-divider content-position="left">匹配规则</el-divider>
        <p class="rule-description">设置匹配规则，当请求满足规则时返回对应响应。如果没有规则，将返回默认响应。</p>
        
        <div v-for="(rule, index) in mockForm.rules" :key="index" class="rule-item">
          <div class="rule-header">
            <h3>规则 #{{ index + 1 }}</h3>
            <el-button 
              type="danger" 
              size="small" 
              icon="Delete" 
              circle 
              @click="removeRule(index)"
            ></el-button>
          </div>
          
          <el-form-item :label="'规则类型'">
            <el-select v-model="rule.type" placeholder="请选择规则类型">
              <el-option label="路径参数" value="path"></el-option>
              <el-option label="查询参数" value="query"></el-option>
              <el-option label="请求头" value="header"></el-option>
              <el-option label="请求体" value="body"></el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item :label="'参数名'">
            <el-input v-model="rule.key" placeholder="请输入参数名"></el-input>
          </el-form-item>
          
          <el-form-item :label="'操作符'">
            <el-select v-model="rule.operator" placeholder="请选择操作符">
              <el-option label="等于" value="eq"></el-option>
              <el-option label="不等于" value="neq"></el-option>
              <el-option label="包含" value="contains"></el-option>
              <el-option label="正则匹配" value="regex"></el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item :label="'参数值'">
            <el-input v-model="rule.value" placeholder="请输入参数值"></el-input>
          </el-form-item>
          
          <el-divider v-if="index < mockForm.rules.length - 1"></el-divider>
        </div>
        
        <div class="add-rule">
          <el-button type="primary" plain @click="addRule">添加规则</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft, Delete } from '@element-plus/icons-vue'
import axios from 'axios'

const route = useRoute()
const router = useRouter()
const formRef = ref(null)

const loading = ref(false)
const saving = ref(false)

// 判断是创建还是编辑
const isEdit = computed(() => {
  return route.params.id !== undefined
})

// 表单数据
const mockForm = reactive({
  name: '',
  path: '',
  method: 'GET',
  description: '',
  responses: [
    {
      statusCode: 200,
      contentType: 'application/json',
      headers: '',
      body: '{}',
      delay: 0,
      isDefault: true
    }
  ],
  rules: []
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入API名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在2到50个字符之间', trigger: 'blur' }
  ],
  path: [
    { required: true, message: '请输入请求路径', trigger: 'blur' },
    { pattern: /^\/.*/, message: '路径必须以/开头', trigger: 'blur' }
  ],
  method: [
    { required: true, message: '请选择请求方法', trigger: 'change' }
  ]
}

// 获取Mock API详情
const fetchMockAPI = async () => {
  if (!isEdit.value) return
  
  const id = route.params.id
  loading.value = true
  
  try {
    const response = await axios.get(`http://localhost:8080/api/mock/${id}`)
    const data = response.data
    
    // 填充表单数据
    mockForm.name = data.name
    mockForm.path = data.path
    mockForm.method = data.method
    mockForm.description = data.description
    
    // 填充响应数据
    if (data.responses && data.responses.length > 0) {
      mockForm.responses = data.responses.map(resp => ({
        statusCode: resp.status_code,
        contentType: resp.content_type,
        headers: resp.headers,
        body: resp.body,
        delay: resp.delay,
        isDefault: resp.is_default
      }))
    }
    
    // 填充规则数据
    if (data.rules && data.rules.length > 0) {
      mockForm.rules = data.rules.map(rule => ({
        type: rule.type,
        key: rule.key,
        operator: rule.operator,
        value: rule.value
      }))
    }
    
    loading.value = false
  } catch (error) {
    console.error('获取Mock API详情失败:', error)
    ElMessage.error('获取Mock API详情失败')
    loading.value = false
  }
}

// 添加响应
const addResponse = () => {
  mockForm.responses.push({
    statusCode: 200,
    contentType: 'application/json',
    headers: '',
    body: '{}',
    delay: 0,
    isDefault: false
  })
}

// 移除响应
const removeResponse = (index) => {
  // 如果删除的是默认响应，则将第一个响应设为默认
  if (mockForm.responses[index].isDefault && mockForm.responses.length > 1) {
    mockForm.responses[0].isDefault = true
  }
  mockForm.responses.splice(index, 1)
}

// 处理默认响应变更
const handleDefaultChange = (index) => {
  // 如果当前响应被设为默认，则其他响应都设为非默认
  if (mockForm.responses[index].isDefault) {
    mockForm.responses.forEach((resp, i) => {
      if (i !== index) {
        resp.isDefault = false
      }
    })
  } else {
    // 如果当前响应被取消默认，确保至少有一个默认响应
    const hasDefault = mockForm.responses.some(resp => resp.isDefault)
    if (!hasDefault && mockForm.responses.length > 0) {
      mockForm.responses[0].isDefault = true
    }
  }
}

// 添加规则
const addRule = () => {
  mockForm.rules.push({
    type: 'query',
    key: '',
    operator: 'eq',
    value: ''
  })
}

// 移除规则
const removeRule = (index) => {
  mockForm.rules.splice(index, 1)
}

// 保存Mock API
const saveMockAPI = async () => {
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    
    saving.value = true
    
    try {
      // 构建API数据
      const apiData = {
        name: mockForm.name,
        path: mockForm.path,
        method: mockForm.method,
        description: mockForm.description,
        responses: mockForm.responses.map(resp => ({
          status_code: resp.statusCode,
          content_type: resp.contentType,
          headers: resp.headers,
          body: resp.body,
          delay: resp.delay,
          is_default: resp.isDefault
        })),
        rules: mockForm.rules.map(rule => ({
          type: rule.type,
          key: rule.key,
          operator: rule.operator,
          value: rule.value
        }))
      }
      
      let response
      if (isEdit.value) {
        // 更新API
        const id = route.params.id
        response = await axios.put(`http://localhost:8080/api/mock/${id}`, apiData)
        ElMessage.success('Mock API更新成功')
      } else {
        // 创建API
        response = await axios.post('http://localhost:8080/api/mock', apiData)
        ElMessage.success('Mock API创建成功')
      }
      
      saving.value = false
      router.push('/mock')
    } catch (error) {
      console.error('保存Mock API失败:', error)
      ElMessage.error('保存Mock API失败')
      saving.value = false
    }
  })
}

// 返回上一页
const goBack = () => {
  router.push('/mock')
}

onMounted(() => {
  fetchMockAPI()
})
</script>

<style scoped>
.mock-form-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.form-card {
  margin-bottom: 20px;
}

.response-item, .rule-item {
  margin-bottom: 20px;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #f8f8f8;
}

.response-header, .rule-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.add-response, .add-rule {
  margin-top: 20px;
  margin-bottom: 30px;
  display: flex;
  justify-content: center;
}

.rule-description {
  color: #606266;
  margin-bottom: 20px;
}
</style>